import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

// 导入仓库对象
import store from '@/store'
import { reqUserInfo } from '@/api'

import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'

Nprogress.configure({ showSpinner: false })

// 创建路由器对象
const router = new VueRouter({
  routes: [
    {
      path: '/login',
      component: () => import('@/views/login.vue'),
    },
    {
      path: '/',
      component: () => import('@/layout/index.vue'),
      redirect: '/home',
      children: [
        {
          path: 'home',
          component: () => import('@/views/home.vue'),
          meta: {
            title: 'dashboard',
          },
        },
      ],
    },
    {
      path: '/article',
      component: () => import('@/layout/index.vue'),
      redirect: '/article/index',
      meta: {
        title: 'articleManager',
      },
      children: [
        {
          path: 'index',
          component: () => import('@/views/article.vue'),
          meta: {
            title: 'articleList',
          },
        },
      ],
    },
    {
      path: '/media',
      component: () => import('@/layout/index.vue'),
      redirect: '/media/index',
      meta: {
        title: 'mediaManager',
      },
      children: [
        {
          path: 'index',
          component: () => import('@/views/media.vue'),
          name: 'media',
          meta: {
            title: 'mediaList',
          },
        },
      ],
    },
    {
      path: '/test',
      component: () => import('@/views/test.vue'),
    },
  ],
})

// 先保存原始的 VueRoute push方法的引用
const originPush = VueRouter.prototype.push
const originReplace = VueRouter.prototype.replace

// 重写push
VueRouter.prototype.push = function (location, okCallback, failCallback) {
  if (okCallback && failCallback) {
    return originPush.call(this, location, okCallback, failCallback)
  } else {
    return originPush.call(this, location).catch(() => {})
  }
}

VueRouter.prototype.replace = function (location, okCallback, failCallback) {
  if (okCallback && failCallback) {
    return originReplace.call(this, location, okCallback, failCallback)
  } else {
    return originReplace.call(this, location).catch(() => {})
  }
}

// 全局的前守卫导航
router.beforeEach(async (to, from, next) => {
  document.title = to?.meta?.title || '文章管理系统'
  Nprogress.start()
  // 1. 获取token
  let token = store.state.token
  let username = store.state.username
  // 2. 判断token
  if (token) {
    // 有token
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      // 继续判断有没有用户名
      if (username) {
        next()
      } else {
        // 拉取用户信息，在重新设置用户信息到vuex
        try {
          let res = await reqUserInfo()
          store.commit('setUsername', res.data.username)
          next({ ...to })
        } catch (err) {
          // 拉取用户信息失败，直接退出
          store.commit('clearToken')
          store.commit('clearUsername')

          next({ path: '/login' })
        }
      }
    }
  } else {
    // 无token
    if (to.path === '/login') {
      // console.log('无 token => login')
      next()
    } else {
      // console.log('无 token => 想翻墙')
      // 想翻墙-》打回登录页面
      next({ path: '/login', query: { redirect: to.path } })
    }
  }
})

// 全局的后守卫导航
router.afterEach((to, from) => {
  Nprogress.done()
})

// 导出路由对象
export default router
